package com.ideafactory.client.views;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.print.BlueInterface;
import com.ideafactory.client.utils.CommonUtils;
import com.ideafactory.client.utils.FileConstants;
import com.ideafactory.client.utils.FirstEvent;
import com.ideafactory.client.utils.HandleMessageUtils;
import com.ideafactory.client.utils.SdCardUtils;
import com.ideafactory.client.utils.SpUtils;
import com.ideafactory.client.utils.VersionUpdateConstants;
import com.ideafactory.client.utils.caches.CacheUtils;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.utils.versioncontrol.UpdateVersionControl;
import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.APP;
import com.ideafactory.client.ybservice.YbSelfService;

import java.util.HashMap;
import java.util.Map;

import static com.ideafactory.client.ybservice.YbSelfService.checkStatus;
import static com.ideafactory.client.ybservice.YbSelfService.getPrinterStatus;
import static com.ideafactory.client.ybservice.YbSelfService.mUsbDev1;

/**
 * Created by LiuShao on 2016/5/12.
 */
public class MenuToShow {

    private static volatile MenuToShow instance;

    public static MenuToShow getInstance() {
        if (instance == null) {
            synchronized (MenuToShow.class) {
                if (instance == null) {
                    instance = new MenuToShow();
                }
            }
        }
        return instance;
    }

    TextView tv_device_dialog_no;
    TextView tv_device_dialog_in_code;
    TextView tv_device_dialog_cpuinfo;
    TextView tv_device_dialog_inner_capacity;
    TextView tv_device_dialog_sd_capacity;
    TextView tv_device_dialog_version;
    TextView tv_device_dialog_soft_type;
    TextView tv_device_dialog_net_info;
    Button btn_new_version_check;
    TextView tv_device_dialog_xmpp_constatus;
    LinearLayout out_sd_card_path;
    RadioGroup radio_storage_path;

    private TextView tv_Ticketprinter;//小票打印机状态
    private TextView tv_blueToothprinter;//蓝牙打印机状态
    private Button btn_SetBlueprinter;//去连接蓝牙打印机
    private Button btn_SetWifiprinter;//配置wifi打印机

    private View view;
    private Activity mActivity;
    public void showMenu(Activity activity) {
        this.mActivity=activity;
        view = View.inflate(APP.getAPP().getApplicationContext(), R.layout.menu_show_info, null);

        tv_device_dialog_no = (TextView) view.findViewById(R.id.tv_device_dialog_no);
        tv_device_dialog_in_code = (TextView) view.findViewById(R.id.tv_device_dialog_in_code);
        tv_device_dialog_cpuinfo = (TextView) view.findViewById(R.id.tv_device_dialog_cpuinfo);
        tv_device_dialog_inner_capacity = (TextView) view.findViewById(R.id.tv_device_dialog_inner_capacity);
        tv_device_dialog_sd_capacity = (TextView) view.findViewById(R.id.tv_device_dialog_sd_capacity);
        tv_device_dialog_version = (TextView) view.findViewById(R.id.tv_device_dialog_version);
        tv_device_dialog_soft_type = (TextView) view.findViewById(R.id.tv_device_dialog_soft_type);
        tv_device_dialog_net_info = (TextView) view.findViewById(R.id.tv_device_dialog_net_info);
        btn_new_version_check = (Button) view.findViewById(R.id.btn_new_version_check);
        tv_device_dialog_xmpp_constatus = (TextView) view.findViewById(R.id.tv_device_dialog_xmpp_constatus);
        out_sd_card_path = (LinearLayout) view.findViewById(R.id.out_sd_card_path);
        radio_storage_path = (RadioGroup) view.findViewById(R.id.radio_storage_path);
        tv_Ticketprinter= (TextView) view.findViewById(R.id.tv_Ticketprinter);
        tv_blueToothprinter= (TextView) view.findViewById(R.id.tv_blueToothprinter);
        btn_SetBlueprinter= (Button) view.findViewById(R.id.btn_SetBlueprinter);
        btn_SetWifiprinter= (Button) view.findViewById(R.id.btn_SetWifiprinter);
        showDiag(activity);
    }

    private  AlertDialog alertDialog;
    private void showDiag(Activity activity){
        alertDialog = new AlertDialog.Builder(activity).create();
        tv_device_dialog_no.setText(CacheUtils.getSerNumber());
        tv_device_dialog_in_code.setText(CacheUtils.getPwd());
        tv_device_dialog_cpuinfo.setText(CommonUtils.getMaxCpuFreq() + "Ghz");
        tv_device_dialog_inner_capacity.setText(SdCardUtils.getSDDiskCon());

        tv_device_dialog_version.setText(CommonUtils.getVersionName());
        tv_device_dialog_soft_type.setText(VersionUpdateConstants.getServerType());
        tv_device_dialog_net_info.setText(NetUtils.getConnectWifiSsid() + "     ip:" + NetUtils.getIpAdress());
        tv_device_dialog_xmpp_constatus.setText(NetUtils.getXmppConnected());

        checkPrinterState(tv_Ticketprinter,tv_blueToothprinter);//检查打印机连接状态

        //判断sd卡是否存在
        String sdCardPath = SdCardUtils.getNoUsbSdcardPath();
        if (!TextUtils.isEmpty(sdCardPath)) {//外置卡存在
            radio_storage_path.setVisibility(View.VISIBLE);
            out_sd_card_path.setVisibility(View.VISIBLE);
            String outSdcard = SdCardUtils.getAvailaleSize(sdCardPath);
            tv_device_dialog_sd_capacity.setText(outSdcard);
        } else {
            radio_storage_path.setVisibility(View.GONE);
            out_sd_card_path.setVisibility(View.GONE);
        }

        String sdPath = CacheUtils.getSdPath();
        if (!TextUtils.isEmpty(sdPath)) {
            if (sdPath.equals("1") && radio_storage_path.getVisibility() == View.VISIBLE) {//1存储路径是外置sd卡,0存储路径是内置sd卡,保存的是外置的sd卡，而且当前存在
                radio_storage_path.check(R.id.rb_outside_storage_check);
            } else {
                radio_storage_path.check(R.id.rb_inner_storage_check);
            }
        }

        //存储路径的选择项
        radio_storage_path.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (group.getCheckedRadioButtonId()) {
                    case R.id.rb_inner_storage_check:
                        FileConstants.setNewResourcePath(true);
                        CacheUtils.putSdPath("0");
                        break;
                    case R.id.rb_outside_storage_check:
                        FileConstants.setNewResourcePath(false);
                        CacheUtils.putSdPath("1");
                        break;
                }
            }
        });

        checkNewVersion();

        btn_new_version_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.hasNetwork()) {
                    UpdateVersionControl.getInstance().checkUpdate();
                    btn_new_version_check.setEnabled(false);
                    btn_new_version_check.setText(mActivity.getResources().getString(R.string.Downloading));

                }
            }
        });
        alertDialog.setView(view, 0, 0, 0, 0);
        alertDialog.getWindow().setLayout(300, 400);
        alertDialog.show();
    }


    private static final int MAIN_QUERY_PRINTER_STATUS = 0xfe;
    /**
     * 检查打印机连接状态
     */
    private void checkPrinterState(TextView tvPrinter,final TextView tvBlue){
        int isLinked= YbSelfService.getPrinterStatus(YbSelfService.mUsbDev1);
        int iStatus = YbSelfService.checkStatus(isLinked);

        switch (iStatus){
            case 0:
                tvPrinter.setText(mActivity.getResources().getString(R.string.SmallTicketPrinterConnected));
                break;
            case 7:
                tvPrinter.setText(mActivity.getResources().getString(R.string.SmallTicketPrinterOutOfPaper));
                break;
            case 8:

                tvPrinter.setText(mActivity.getResources().getString(R.string.SmallTicketPrinterPaperAlmostOut));
                break;
            default:
                tvPrinter.setText(mActivity.getResources().getString(R.string.SmallTicketPrinterAbnormal));
                break;
        }

        boolean isLikBlue= SpUtils.getBoolean(mActivity,"wifiPrinter",false);
        if (isLikBlue){
            tvBlue.setText(mActivity.getResources().getString(R.string.WIFIPrinterConnected));
        }else{
            tvBlue.setText(mActivity.getResources().getString(R.string.WIFIPrinterNotConnected));
           }
        if(tvBlue.getText().toString().equals(mActivity.getResources().getString(R.string.WIFIPrinterNotConnected))){
            btn_SetBlueprinter.setVisibility(View.VISIBLE);
            btn_SetBlueprinter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String macIp=SpUtils.getString(mActivity,SpUtils.WIFI_IP,null);
                    if (macIp==null){
                        Toast.makeText(mActivity,mActivity.getResources().getString(R.string.PleaseConfigureWifiPrinterFirst),Toast.LENGTH_SHORT).show();

                        return;
                    }

                    btn_SetBlueprinter.setEnabled(false);
                    btn_SetBlueprinter.setBackgroundResource(R.color.left_text);
                    btn_SetBlueprinter.setText(mActivity.getResources().getString(R.string.connecting));

//                    if (YbSelfService.mGpService!=null){
//                        try {
//                            YbSelfService.mGpService.openPort(0, 3, macIp, 9100);
//                            setBlueInterface(new BlueInterface() {
//                                @Override
//                                public void BlueListen(boolean isConnected) {
//                                    if (isConnected){
//                                        tvBlue.setText(mActivity.getResources().getString(R.string.WIFIPrinterConnected));
//                                        btn_SetBlueprinter.setVisibility(View.GONE);
//                                        btn_SetWifiprinter.setVisibility(View.GONE);
//                                    }else {
//                                        tvBlue.setText(mActivity.getResources().getString(R.string.WIFIPrinterNotConnected));
//                                    }
//                                }
//                            });
//                        } catch (RemoteException e) {
//                            e.printStackTrace();
//                        }
//                    }
                }
            });

            btn_SetWifiprinter.setVisibility(View.VISIBLE);
            btn_SetWifiprinter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setWifiPrinter();
                }
            });
        }

    }

    private void setWifiPrinter() {

        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog, null);
        final EditText numEt = (EditText) view.findViewById(R.id.editText1);
        final Button setting = (Button) view.findViewById(R.id.button_setting);
        final AlertDialog builder=new AlertDialog.Builder(mActivity).setTitle(mActivity.getResources().getString(R.string.str_printset)).setView(view).setCancelable(true).create();
        setting.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(numEt.getEditableText().toString())) {
                    SpUtils.saveString(mActivity,SpUtils.WIFI_IP,numEt.getEditableText().toString());
                    builder.dismiss();
                }
            }
        });
        builder.show();
    }


    public  BlueInterface blueInterface;

    private void setBlueInterface(BlueInterface blueInterface) {
        this.blueInterface = blueInterface;
    }

    /**
     * 检查是否有新版本
     */
    private void checkNewVersion() {
        Map paramMap = new HashMap();
        paramMap.put("clientVersion", CommonUtils.getVersionName());
        paramMap.put("type", VersionUpdateConstants.CURRENT_VERSION + "");
        NetUtils.Post(NetConstants.VERSION_URL, paramMap, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                 HandleMessageUtils.getInstance().sendHandler(NEWVERSIONCHECK, switchDialogHandler, result);
            }
        });
    }

    private static final int NEWVERSIONCHECK = 0x159652;
    private Handler switchDialogHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NEWVERSIONCHECK:
                    String newVersion = (String) msg.obj;
                    if (alertDialog.isShowing()) {
                        if (!newVersion.equals("\"1\"")) {
                            btn_new_version_check.setVisibility(View.VISIBLE);
                            btn_new_version_check.setText(mActivity.getResources().getString(R.string.ClickUpdate));
                        }else{
                            btn_new_version_check.setVisibility(View.INVISIBLE);
                        }
                    }
                    break;
                case 1:
                    tv_blueToothprinter.setText(mActivity.getResources().getString(R.string.BluetoothPrinterNotConnected));
                    break;
                case 2:
                    tv_blueToothprinter.setText(mActivity.getResources().getString(R.string.BluetoothPrinterConnected));
                    break;
            }
        }
    };


}
